﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Xml.Linq;
using Acando.Dynamics.CRM.Silverlight.Library.Interfaces;
using Acando.Dynamics.CRM.Silverlight.Library.MetaSdk;

namespace RiaCrm.DynamicEntityGrid
{
    public partial class DynamicEntityGridView : UserControl, IPage
    {
        private DynamicEntityGridViewModel _viewModel;

        public DynamicEntityGridView(DynamicEntityGridViewModel viewModel)
        {
            InitializeComponent();
           
            this.DataContext = viewModel;
            this._viewModel = viewModel;
            this._viewModel.LoadingItemsStart += (sender, args) => this.pnlLoading.Visibility = Visibility.Visible;
            this._viewModel.LoadingItemsCompleted += (sender, args) => this.pnlLoading.Visibility = Visibility.Collapsed;
            this._viewModel.PropertyChanged += new PropertyChangedEventHandler(viewModel_PropertyChanged);
            this._viewModel.LoadItems();
            this.OnLoadLayoutXmlCompleted(this._viewModel.LayoutXml);
            

        }
        private void viewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "LayoutXml")
            {
                this.OnLoadLayoutXmlCompleted(this._viewModel.LayoutXml);
            }
        }

        private void OnLoadLayoutXmlCompleted(String layoutxml)
        {
            this.ViewDataGrid.Columns.Clear();


            if (!String.IsNullOrEmpty(layoutxml) && !String.IsNullOrEmpty(layoutxml.Trim()))
            {
                var colXml = XDocument.Parse(layoutxml);

                foreach (var cell in colXml.Element("grid").Element("row").Elements("cell"))
                {
                    var fieldName = cell.Attribute("name").Value;
                    AttributeMetadata attrMeta = null;
                    
                    if (fieldName.Contains(".")) // sample: 'accountprimarycontactidcontactcontactid.emailaddress1'
                    {
                        String head = fieldName.Split(new char[] { '.' })[0];   // e.g.: 'accountprimarycontactidcontactcontactid'
                        String tail = fieldName.Split(new char[] { '.' })[1];   // e.g.: 'emailaddress1'

                        // In case the view uses a field of a refereneced Entity, the metaData needs to be loaded in addition
                        foreach (var relationship in this._viewModel.EntityMetadata.ManyToOneRelationships)
                        {
                            
                            String fullname = String.Format("{0}{1}{2}{3}", relationship.ReferencingEntity,
                                                                            relationship.ReferencingAttribute,
                                                                            relationship.ReferencedEntity, 
                                                                            relationship.ReferencedAttribute);

                            if (fullname.ToLower() == head.ToLower())
                            {
                                // add placeholder to grid (--> will later [after metadataLoading] be replace by correct column)
                                this.ViewDataGrid.Columns.Add(new Column_placeholder(){ ColumnFieldname = tail});
                                // Load metaData for refrenced Entity:
                                this._viewModel.Metadatalayer.LoadMetaData(relationship.ReferencedEntity, LoadMetaDataCallback);
                            }
                        }
                    }
                    else // Column belongs to the current Entity
                    {
                        attrMeta = this._viewModel.EntityMetadata.GetAttributeMetadata(fieldName);

                        this.ViewDataGrid.Columns.Add(new DynamicEntityDataGridColumn(this._viewModel,
                                                                                      attrMeta.AttributeType.Value.ToString(),
                                                                                      fieldName,
                                                                                      attrMeta.DisplayName.UserLocLabel.Label,
                                                                                      this._viewModel.EntityMetadata,
                                                                                      !attrMeta.ValidForUpdate.Value));
                    }
                }
            }
        }

        private void LoadMetaDataCallback(EntityMetadata metaDataObj)
        {
            // find corresponding placeholder: (bei der Reports entity kommt "Could not find Placeholder ")
            for(int index = 0; index < this.ViewDataGrid.Columns.Count(); index++)
            {
                if(this.ViewDataGrid.Columns[index].GetType() == typeof(Column_placeholder))
                {
                    Column_placeholder column = (Column_placeholder)this.ViewDataGrid.Columns[index];

                    if(metaDataObj.GetAttributesDict().ContainsKey(column.ColumnFieldname))
                    {
                        var attrMeta = metaDataObj.GetAttributeMetadata(column.ColumnFieldname);

                        var newColumn = new DynamicEntityDataGridColumn(this._viewModel,
                                                                   attrMeta.AttributeType.Value.ToString(),
                                                                   column.ColumnFieldname,
                                                                   attrMeta.DisplayName.UserLocLabel.Label,
                                                                   this._viewModel.EntityMetadata,
                                                                   !attrMeta.ValidForUpdate.Value);

                        this.ViewDataGrid.Columns.RemoveAt(index);
                        this.ViewDataGrid.Columns.Insert(index, newColumn);

                        return;
                    }
                }
            }

            throw new Exception("Could not find Placeholder ");
        }

        #region IPage Members

        public Panel ParentElementForDialogs
        {
            get { return this.LayoutRoot; }
        }

        #endregion
    }
}
